﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using OfficeOpenXml;
using System.IO;
using OfficeOpenXml.Drawing;

namespace BusinessLogic
{
    public static class ExcelCreator
    {
        public static byte[] Create(ExcelCreatorData data)
        {
            byte[] arr = null;

            using(ExcelPackage pck = new ExcelPackage())
            {
                pck.Load(new FileStream(data.TemplatePath, FileMode.Open, FileAccess.Read, FileShare.Read));
                
                if (pck.Workbook.Worksheets.Count > 0)
                {
                    //Create the worksheet
                    ExcelWorksheet ws = pck.Workbook.Worksheets[1];

                    foreach(var o in data.Data)
                    {
                        if(o.Key.Type.Equals(eExcelCreatorDataObjectType.CELL))
                        {
                            if(!string.IsNullOrWhiteSpace(o.Value))
                            {
                                ws.Cells[o.Key.Name].LoadFromText(o.Value);
                            }
                        }
                        else if(o.Key.Type.Equals(eExcelCreatorDataObjectType.SHAPE))
                        {
                            var rt = (ws.Drawings[o.Key.Name] as ExcelShape);

                            if(rt != null)
                            {
                                if(!string.IsNullOrWhiteSpace(o.Value))
                                {
                                    rt.Text = string.Concat(rt.Text, " ", o.Value);
                                }
                            }
                        }
                    }
                }      

                arr = pck.GetAsByteArray();
            }

            return arr;
        }
    }
}